The for-loop is a control structure used to repeat a block of code for a specified number of iterations. It consists of three parts: initialization, condition, and update. The loop starts with the initialization step, followedby the condition check. If the condition is true, the code inside the loop is executed, and then the update step is performed. The loop continues as long as the condition remains true.
for (initialization; condition; update) {
// Code to be repeated
}
In this program, use a for loop to print the numbers from 1 to 5, each on a new line.
#include <stdio.h>
int main() {
// Initialization: Set the loop control variable 'i' to 1
// Condition: The loop will continue as long as 'i' is less than or equal to 5
// Update: Increment 'i' by 1 after each iteration
for (int i = 1; i <= 5; i++) {
printf("%d\n", i); // Print the value of 'i' on a new line
}
return 0;
}
1
2
3
4
5
In the output, can see that the loop has printed the numbers from 1 to 5, each on a new line, as specified by the for loop's initialization, condition, and update.
What is a for-loop in C?
What is the initialization part of a for-loop responsible for?
What does the condition part of a for-loop determine?
What is the role of the increment part in a for-loop?
What is the primary purpose of using a for-loop in C?